package com.yulinlin.jdbc.model.wrapper;

import com.yulinlin.jdbc.model.anno.JoinPrimary;
import com.yulinlin.lang.util.ReflectionUtil;
import com.yulinlin.lang.util.StringUtil;
import com.yulinlin.jdbc.model.anno.JoinField;
import com.yulinlin.jdbc.model.anno.JoinTable;
import com.yulinlin.jdbc.model.anno.JoinWhere;
import com.yulinlin.jdbc.session.SqlSession;
import com.yulinlin.core.wrapper.IDeleteWrapper;
import com.yulinlin.core.wrapper.IStringConditionWrapper;

import java.lang.reflect.Field;
import java.util.List;

public class ModelDeleteWrapper<E>  {

    private IDeleteWrapper<E,ModelDeleteWrapper<E>> wrapper;

    public ModelDeleteWrapper() {
        this.wrapper =   SqlSession.session().ofDelete(this);
    }


    public void parse(Object obj){

        JoinTable table =  obj.getClass().getAnnotation(JoinTable.class);
        if(table != null){
            wrapper.table(table.value());
        }

        List<Field> fs =  ReflectionUtil.getAllDeclaredFields(obj.getClass());

        for (Field f : fs){

            //必须有主键
            JoinPrimary joinPrimary =    f.getAnnotation(JoinPrimary.class);
            if(joinPrimary == null){
                continue;
            }

            JoinField joinField =    f.getAnnotation(JoinField.class);
            if(joinField == null){
                continue;
            }


            String columnName =  joinField.columnName();
            if(columnName.length() == 0){
                columnName = StringUtil.javaToColumn(f.getName());
            }


            JoinWhere joinWhere =    f.getAnnotation(JoinWhere.class);
            Object value =  ReflectionUtil.invokeGetter(obj,f.getName());

            if(value == null){
                continue;
            }
            IStringConditionWrapper whereWrapper ;

            whereWrapper = wrapper.where();

            ConditionUtil.condition(whereWrapper,joinWhere.and(),columnName,joinWhere.condition(),value);


        }

    }


    public IDeleteWrapper<E,ModelDeleteWrapper<E>>  wrapper(){
        return  wrapper;
    }

    public int execute(){
        SqlSession session =   SqlSession.session();
        return session.execute(this.wrapper);
    }

    public static <E> ModelDeleteWrapper newInstance(E obj){
        ModelDeleteWrapper wrapper =   new ModelDeleteWrapper();
        wrapper.parse(obj);
        return  wrapper;
    }


}
